/**
 *该模块依赖文件如下
 *    样式表:bootstrap
 *    js:jquery ui-bootstrap-tpls
 *模块：qf.common
 *service:  defendAgain    //防止重复提交
 *          dialogService  //模态对话框服务
 */
'use strict';

var commonModule = angular.module('qf.common', ['ui.bootstrap']);

//防止重复提交
commonModule
    .service('defendAgain', [
        '$rootScope',
        function($rootScope) {
            var self = this;
            self.isActionWorking = false;

            self.notifyActionWorking = function() {
                self.isActionWorking = true;
            };
            self.notifyActionWorkOver = function() {
                self.isActionWorking = false;
            };

            self.isHasWorkRuning = function() {
                return self.isActionWorking;
            };

            $rootScope.isHasWorkRuning = self.isHasWorkRuning;
        }
    ]);

//弹出框
commonModule
    .service('dialogService', ['$modal', function($modal) {
        //确认框模板
        this.confirmTemplate = ['<div class="modal-header">',
            '  <button type="button" class="close" ng-click="cancel()">',
            '    <span>&times;</span></button>',
            '  <h4 class="modal-title">{{title}}</h4>',
            '</div>',
            '<div class="modal-body">',
            ' <p>{{msg}}</p>',
            '</div>',
            '<div class="modal-footer">',
            '  <button class="btn btn-sm btn-success" type="button" ng-click="ok()">确定</button>',
            '  <button class="btn btn-sm btn-default" type="button" ng-click="cancel()">取消</button>',
            '</div>',
        ].join('');

        //消息框模板
        this.showmessageTemplate = ['<div class="modal-header">',
            '  <button type="button" class="close" ng-click="cancel()">',
            '    <span>&times;</span></button>',
            '  <h4 class="modal-title">{{title}}</h4>',
            '</div>',
            '<div class="modal-body">',
            ' <p>{{msg}}</p>',
            '</div>',
            '<div class="modal-footer">',
            '  <button class="btn btn-sm btn-success" type="button" ng-click="ok()">确定</button>',
            '</div>',
        ].join('');

        //显示数据框模板
        this.showObjectTemplate = ['<div class="modal-header">',
            '  <button type="button" class="close" ng-click="cancel()">',
            '    <span>&times;</span></button>',
            '  <h4 class="modal-title">{{title}}</h4>',
            '</div>',
            '<div class="modal-body">',
            ' <pre>{{obj|json}}</pre>',
            '</div>',
            '<div class="modal-footer">',
            '  <button class="btn btn-sm btn-success" type="button" ng-click="ok()">确定</button>',
            '</div>',
        ].join('');

        //图片框模板,可拖动
        this.imageBoxTemplate = ['<style>',
            '.modal-header .close {',
            'width: 26px;',
            'height: 26px;',
            'background: url(images/Shape-9.png) 0 0 no-repeat;',
            'border: none !important;',
            '}',
            '.imgbox {',
            'display: inline-block;',
            'padding: 0 40px 40px 40px;',
            'font-size: 14px;',
            '}',
            '.imgbox img {',
            'height: auto;',
            'width: auto;',
            'max-height: 100%;',
            'max-width: 760px;',
            'overflow: hidden;',
            'display: block;',
            'margin-bottom: 10px;',
            '}',
            '.btn-prev,',
            '.btn-next {',
            'display: inline-block;',
            'width: 24px;',
            'height: 48px;',
            'margin-bottom: 200px;',
            '}',
            '.btn-prev:hover,',
            '.btn-next:hover {',
            'cursor: pointer;',
            '}',
            '.btn-prev {',
            'background: url(images/an_06_mormal.png) 0 0 no-repeat;',
            '}',
            '.btn-next {',
            'background: url(images/an_06_move.png) 0 0 no-repeat;',
            '}',
            '</style>',
            '<div draggable class="modal-header">',
            '<h4 class="modal-title">{{title}}</h4>',
            '<a class="close" ng-click="cancel()" title="关闭"></a>',
            '</div>',
            '<div class="modal-body">',
            '<a class="btn-prev" ng-click="prevImg()" title="上一张"></a>',
            '<div class="imgbox">',
            '<img alt="{{getCurrPic(currIndex).FILENAME}}" ng-src="api/resource/{{getCurrPic(currIndex).PICID}}" />',
            '<span>{{getCurrPic(currIndex).FILENAME}}</span>',
            '</div>',
            '<a class="btn-next" ng-click="nextImg()" title="下一张"></a>',
            '</div>'
        ].join('');

        //显示确认/取消提示框
        this.confirm = function(op, okCallback, cancelCallback) {
            var self = this;
            var modalInstance = $modal.open({
                animation: true,
                template: op.template || self.confirmTemplate,
                controller: 'ModalInstanceCtrl',
                size: op.size || 'md',
                resolve: {
                    title: function() {
                        return op.title || '确认';
                    },
                    msg: function() {
                        return op.msg || '确定执行吗?';
                    }
                }
            });

            modalInstance.result.then(function() {
                if (okCallback) {
                    okCallback();
                }
            }, function() {
                if (cancelCallback) {
                    cancelCallback();
                }
            });
        };

        //显示消息提示框
        this.showmessage = function(op, cb) {
            var self = this;
            var modalInstance = $modal.open({
                animation: true,
                template: op.template || self.showmessageTemplate,
                controller: 'ModalInstanceCtrl',
                size: op.size || 'sm',
                resolve: {
                    title: function() {
                        return op.title || '提示信息';
                    },
                    msg: function() {
                        return op.msg || 'OK!';
                    }
                }
            });

            modalInstance.result.then(function() {
                if (cb) {
                    cb();
                }
            }, function() {
                if (cb) {
                    cb();
                }
            });
        };

        //显示数据提示框
        this.showobj = function(op, cb) {
            var self = this;
            var modalInstance = $modal.open({
                animation: true,
                template: op.template || self.showObjectTemplate,
                controller: 'ModalInstanceForObjCtrl',
                size: op.size || 'sm',
                resolve: {
                    title: function() {
                        return op.title || 'json';
                    },
                    obj: function() {
                        return op.obj || {};
                    }
                }
            });

            modalInstance.result.then(function() {
                if (cb) {
                    cb();
                }
            });
        };

        //显示图像盒子框
        this.showImageBox = function(op, cb) {
            var self = this;
            var modalInstance = $modal.open({
                animation: true,
                template: op.template || self.imageBoxTemplate,
                controller: 'ModalInstanceForImageCtrl',
                size: op.size || 'lg',
                resolve: {
                    title: function() {
                        return op.title || '';
                    },
                    images: function() {
                        return op.images || [];
                    },
                    currIndex: function() {
                        return op.currIndex || 0;
                    }
                }
            });

            modalInstance.result.then(function() {
                if (cb) {
                    cb();
                }
            });
        }
    }])
    .controller('ModalInstanceCtrl', ['$scope', '$modalInstance', 'title', 'msg',
        function($scope, $modalInstance, title, msg) {
            $scope.title = title;
            $scope.msg = msg;
            $scope.ok = function() {
                $modalInstance.close();
            };

            $scope.cancel = function() {
                $modalInstance.dismiss();
            };

        }
    ])
    .controller('ModalInstanceForObjCtrl', ['$scope', '$modalInstance', 'title', 'obj',
        function($scope, $modalInstance, title, obj) {
            $scope.title = title;
            $scope.obj = obj;
            $scope.ok = function() {
                $modalInstance.close();
            };

            $scope.cancel = function() {
                $modalInstance.dismiss();
            };

        }
    ])
    .controller('ModalInstanceForImageCtrl', ['$scope', '$modalInstance', '$timeout', 'title', 'images', 'currIndex', function($scope, $modalInstance, $timeout, title, images, currIndex) {
        //打开模态框，显示当前选中照片

        $scope.title = title;
        $scope.currIndex = currIndex;
        $scope.images = images;

        //重设模态框样式
        function setModalCss() {
            //按钮底边距为(图片盒高度-按钮高度)/2
            var imgBox = $('.imgbox'),
                btn = $('.btn-prev,.btn-next');
            var marginHeight = (imgBox.innerHeight() - btn.outerHeight()) / 2;
            btn.css('margin-bottom', marginHeight + 'px');
            //btnNext.css('margin-bottom', marginHeight + 'px');
            /*当图片盒宽度+按钮宽度>模态框体宽度时，模态框体宽度=图片盒宽度+按钮宽度+84*/
            if (btn.outerWidth(true) * 2 + imgBox.outerWidth(true) + 104 > 900) {
                var modalWidth = btn.outerWidth(true) * 2 + imgBox.outerWidth(true) + 104;
                $('.modal-dialog').css('width', modalWidth + 'px');
            } else {
                $('.modal-dialog').css('width', '900px');
            }
        }

        $scope.getCurrPic = function(index) {
            return $scope.images[index];
        };

        $scope.prevImg = function() {
            $scope.currIndex = ($scope.currIndex === 0) ? 0 : ($scope.currIndex - 1);
        };

        $scope.nextImg = function() {
            $scope.currIndex = ($scope.currIndex === $scope.images.length - 1) ? $scope.images.length - 1 : ($scope.currIndex + 1);
        };

        $scope.getCurrPic = function(index) {
            return $scope.images[index];
        };

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };

        $scope.$watch('currIndex', function() {
            //图像变化时,重算图片按钮居中
            $timeout(function() { setModalCss(); }, 80);
        });
    }]);

//模态框拖动效果
commonModule.directive('draggable', ['$document', function($document) {
    return function(scope, element, attr) {
        var startX = 0,
            startY = 0,
            x = 0,
            y = 0;
        element = angular.element($('.modal-dialog'));
        element.css({
            //position: 'relative',
            cursor: 'move'
        });

        element.on('mousedown', function(event) {
            // Prevent default dragging of selected content
            event.preventDefault();
            startX = event.pageX - x;
            startY = event.pageY - y;
            $document.on('mousemove', mousemove);
            $document.on('mouseup', mouseup);
        });

        function mousemove(event) {
            y = (event.pageY === startY) ? parseFloat(element.css('top')) : (event.pageY - startY);
            x = (event.pageX === startX) ? parseFloat(element.css('left')) : (event.pageX - startX);
            element.css({
                top: y + 'px',
                left: x + 'px'
            });
        }

        function mouseup() {
            $document.off('mousemove', mousemove);
            $document.off('mouseup', mouseup);
        }
    };
}]);
